<?php
namespace app\modules\epi\controllers;

use Yii;
use yii\db\Expression;
use ac\controllers\AuthController;
use app\models\OrderInfo;
use app\models\OrderInfoSearch;
use app\models\Goods;
use app\models\GoodsSearch;
use app\models\GoodsCategory;
use ac\component\exception\ErrMap;
use ac\component\tool\Tool;
use app\models\OperationLog;
use ac\behaviors\Sort;
use yii\helpers\Html;


class OrderController extends AuthController
{


    /*订单列表*/
    public function actionOrderList()
    {
        if(isset($this->get['page'])){
            $currPage = intval($this->get['page']?$this->get['page']:1);
        }else{
            $currPage = 1;
        }
        if(isset($this->get['pagesize'])){
            $pageSize = intval($this->get['pagesize']?$this->get['pagesize']:Tool::getPageSize());
        }else{
            $pageSize = Tool::getPageSize();
        }
        // P($this->get);
        $search = (new OrderInfoSearch())->search($this->get);
        if($search === false){//验证搜索参数不通过
            $count = 0;
            $orderList = array();
        }else{
            $count = $search->count();
            $orderList = $search->joinWith('member')
                          ->offset($pageSize*($currPage-1))->limit($pageSize)
                          ->orderBy([
                                'add_time' => SORT_DESC
                            ])
                          // ->createCommand()->getRawSql();
                          ->asArray()->all();
            if(!is_null($orderList)) {
                foreach($orderList as $k => $v) {
                    $orderList[$k]["order_amount"] = $orderList[$k]["order_amount"]/100;
                }
            }
        }

        // P($orderList);
        $res = array(
            'list' => $orderList,
            'pageInfo' => array(
                'count' => intval($count),
                'currPage' => $currPage,
                'pageSize' => $pageSize,
            ),
        );
        return Tool::showRes([0, '获取成功'], $res);
    }

    /*添加订单*/
    public function actionAddOrder()
    {
        if(Yii::$app->request->isPost){
            // P($this->post);

            $orderInfo = new OrderInfo;
            $transaction = Yii::$app->db->beginTransaction();//事物处理
            $pass = true;
            try{
                /*1、添加备案*/
                if(!$order_id = $orderInfo->addOrder($this->post)){
                    $pass = false;
                    if($orderInfo->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $orderInfo->getErrors();//异常信息
                    }else{
                        throw new \Exception('添加备案失败');
                    }
                }
                // P($order_id);

                $num = count($this->post['OrderInfo']['goodsInfo']);
                for($i = 0; $i < $num; $i++) {
                    /*2、添加鉴品*/
                    $goods = new Goods;
                    $data = [
                        "Goods" => $this->post['OrderInfo']['goodsInfo'][$i]
                    ];
                    $data["Goods"]["order_id"] = $order_id;
                    // P($data);
                    if(!$goods_id = $goods->addGoods($data)){
                        $pass = false;
                        if($goods->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $goods->getErrors();//异常信息
                        }else{
                            throw new \Exception('添加备案失败');
                        }
                    }

                    /*3.增加此分类的鉴品数量， 其他分类不增加*/
                    GoodsCategory::updateAllCounters(['content_count' => 1], 'catid = :id', [':id' => $this->post['OrderInfo']['goodsInfo'][$i]['catid']]);
                }

                if($pass){
                    $backInfo = [0, '添加备案成功'];//返回信息
                    $transaction->commit();
                }
            }catch(\Exception $exception){
                $transaction->rollback();       
            };
        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }


    /*确定订单*/
    public function actionConfirmOrder()
    {
        // P($this->post);
        /*如果有数据，进行修改*/
        if(Yii::$app->request->isPost){
            $id = isset($this->post['id'])?intval($this->post['id']):'';
            if(!$id){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                $orderInfo = new OrderInfo;
                $data["OrderInfo"]["order_status"] = 2;
                if($orderInfo->modifyOrder($data, $id)){
                    $backInfo = [0, '确认订单成功'];//返回信息
                }else{
                    if($orderInfo->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $orderInfo->getErrors();//异常信息
                    }
                }
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }

        return Tool::showRes(ErrMap::getError(10005));
    }



}
